<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="./css/font-awesome.min.css">
    <link rel="stylesheet" href="./css/cropper.css">
    <link rel="stylesheet" href="./css/main.css">
    <link rel="stylesheet" href="/public/templateUI/publicStyle.css" />
    <style>
        .btnStyle{
            border-radius: 5px;
        }
        .img-container{
            visibility: hidden;
        }
    </style>
</head>
<body>
<div style="padding: 20px 50px">
    <form class="layui-form" action="" lay-filter="img">
        <div class="layui-input-inline">
            <select name="img_type" lay-filter="img_type">
                <option value="1">原图</option>
                <option value="2">16:9</option>
                <option value="3">4:3</option>
                <option value="4">1:1</option>
            </select>
        </div>
        <button type="button" style="margin-left: 10px" id="ueditor-imgUpload-Btn" class="layui-btn layui-btn-normal">上传图片</button>
    </form>
    <div class="img-container">
        <img id="image" src="" alt="Picture">
    </div>
    <div style="text-align: center;margin-top: 30px">
        <button type="button" class="layui-btn layui-btn-sm confirm layui-btn-normal btnStyle">确定</button>
        <button type="button" class="layui-btn layui-btn-sm cancel layui-btn-primary btnStyle">取消</button>
    </div>
</div>


<script src="../../third-party/jquery-1.10.2.js"></script>
<script type="text/javascript" src="../internal.js"></script>
<script src="./js/cropper.js"></script>
<script src="./js/jquery-cropper.js"></script>
<script src="/public/templateUI/layui/layui.all.js"></script>
<script type="text/javascript" src="/public/transcode.js"></script>
<script src="/public/ossUploadJs/myOssSdk.js" type="text/javascript" charset="utf-8"></script>
<script src="/public/ossUploadJs/uploadAliyun.js" type="text/javascript" charset="utf-8"></script>
<script>

    var $image = $('#image');
    var options = {
        preview: '.img-preview',
        cropBoxMovable: false,
        viewMode: 1,
        movable: true,
        background: false,
        center: true,
        dragMode:'move',
        cropBoxResizable: false,
        crop: function (e) {
            // console.log(e)
            // $dataX.val(Math.round(e.detail.x));
            // $dataY.val(Math.round(e.detail.y));
            // $dataHeight.val(Math.round(e.detail.height));
            // $dataWidth.val(Math.round(e.detail.width));
            // $dataRotate.val(e.detail.rotate);
            // $dataScaleX.val(e.detail.scaleX);
            // $dataScaleY.val(e.detail.scaleY);
            // console.log($image.cropper('getData', true));
            // var cas=$image.cropper('getCroppedCanvas');
            // var base64url=cas.toDataURL('image/jpeg');
            // cas.toBlob(function (e) {
            //     console.log(e);  //生成Blob的图片格式
            // })
            // $("#imgShow").attr('src',base64url)
        }
    };
    var form = layui.form;
    var imgType = 1;
    $image.cropper('destroy').cropper(options);
    // Cropper
    $image.on({
        ready: function (e) {
            var imgWidth = $image.cropper('getImageData').width;
            var imgHeight = $image.cropper('getImageData').height;
            $image.cropper('setCropBoxData',{width:imgWidth,height:imgHeight,left:0,top:0}).cropper(options);
        },
        cropstart: function (e) {
            //console.log(e.type, e.detail.action);
        },
        cropmove: function (e) {
            //console.log(e.type, e.detail.action);
        },
        cropend: function (e) {
            //console.log(e.type, e.detail.action);
        },
        crop: function (e) {
            // console.log(e.type);
        },
        zoom: function (e) {
            //console.log(e.type, e.detail.ratio);
        }
    }).cropper(options);
    //监听选择
    form.on('select(img_type)', function(data){
        imgType = data.value;
        imageChange();
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });

    layui.use('upload', function() {
        var $ = layui.jquery
            , upload = layui.upload;
        //普通图片上传
        var uploadInst = upload.render({
            elem: '#ueditor-imgUpload-Btn'
            , auto: false
            ,headers: {token:localStorage.getItem("token")}
            , url: '/api/Upload/allUpload'
            ,accept: 'file' //普通文件
            ,exts: 'png|jpg|jpeg' //只允许上传压缩文件
            , before: function () {
                var transcode = new TransCode();
                var headers = transcode.httpsHeaders(1); //用变量接收，然后加入接口请求的headers中
                uploadInst.config.headers = transcode.httpsHeaders(1);
            }
            , choose: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result) {
                    form.val('img',{img_type:1})
                    $(".img-container").css('visibility','visible');
                    $("#image").attr('src',result);
                    $image.cropper('replace',result,false );
                    imageChange();
                });
            }
            , done: function (res) {
                // layer.closeAll();
                if(res.code==200){

                }else{
                    layer.msg(res.msg)
                }
                //上传成功
            }
            , error: function () {
                // window.parent.UE.getEditor('editor').execCommand('insertHtml', '图片')
                layer.msg("网络错误，请稍后再试")
            }
        });
    });

    function imageChange(){
        // $image.cropper('reset');
        // alert(imgType)
        var imgWidth = $image.cropper('getImageData').width;
        var imgHeight = $image.cropper('getImageData').height;
        if (imgType==1){
            $image.cropper('setCropBoxData',{width:imgWidth,height:imgHeight,left:0,top:0}).cropper(options);
        } else if (imgType==2){
            if (imgWidth<=imgHeight){
                var BoxWidth = imgWidth;
                var BoxHeight = parseInt(9 * BoxWidth / 16);
                $image.cropper('setCropBoxData',{width:BoxWidth,height:BoxHeight,left:0,top:(imgHeight-BoxHeight)/2}).cropper(options);
            } else {
                var BoxHeight = imgHeight;
                var BoxWidth =  parseInt(16 * BoxHeight / 9);
                console.log(imgHeight)
                console.log(BoxWidth)
                $image.cropper('setCropBoxData',{width:BoxWidth,height:BoxHeight,left:(imgWidth-BoxWidth)/2,top:0}).cropper(options);
            }
            // options.aspectRatio = 16 / 9;
            // $image.cropper('destroy').cropper(options);
        } else if (imgType==3){
            if (imgWidth<=imgHeight){
                var BoxWidth = imgWidth;
                var BoxHeight = parseInt(3 * BoxWidth / 4);
                $image.cropper('setCropBoxData',{width:BoxWidth,height:BoxHeight,left:0,top:(imgHeight-BoxHeight)/2}).cropper(options);
            } else {
                var BoxHeight = imgHeight;
                var BoxWidth =  parseInt(4 * BoxHeight / 3);
                $image.cropper('setCropBoxData',{width:BoxWidth,height:BoxHeight,left:(imgWidth-BoxWidth)/2,top:0}).cropper(options);
            }
            // options.aspectRatio = 4 / 3;
            // $image.cropper('destroy').cropper(options);
        } else if (imgType==4){
            if (imgWidth<=imgHeight){
                var BoxWidth = imgWidth;
                var BoxHeight = imgWidth;
                $image.cropper('setCropBoxData',{width:BoxWidth,height:BoxHeight,left:0,top:(imgHeight-BoxHeight)/2}).cropper(options);
            } else {
                var BoxHeight = imgHeight;
                var BoxWidth =  imgHeight;
                $image.cropper('setCropBoxData',{width:BoxWidth,height:BoxHeight,left:(imgWidth-BoxWidth)/2,top:0}).cropper(options);
            }
        }
    }

    $(".confirm").click(function () {
        if ($("#image").attr('src')==""){
            layer.msg('请先上传图片');
            return false
        }
        var index = layer.load(1, {
            shade: [0.2,'#333333'] //0.1透明度的白色背景
        });
        var cas = $image.cropper('getCroppedCanvas');
        var base64url=cas.toDataURL('image/png');
        imageUpload(base64url,cas.width,cas.height)
        return false
    });
    $(".cancel").click(function () {
        dialog.close();
        return false
    });
    function imageUpload(data,width,height){
        var file = dataURLtoFile(data,'ueditor_img_'+new Date().getTime()+'.png')
        var formData = new FormData();
        formData.append('file', file);
        GlobalUploadFile(file, 'image', function (res) {
            var image = res.path;
            layer.closeAll();
            editor.execCommand('insertHtml', '<img data-width="'+width+'" data-height="'+height+'" style="max-width: 100%!important;" _src="'+image+'" src="'+image+'">');
            dialog.close();
            // postHttpAjax("/system/system/setBackGroupPic", {BackGroupPic: image})
            // $('#banner_path').attr("src", res.path);
            //$("#path").val(res.path);
        }, function (err) {
            console.log(err)
            layer.closeAll();
            layer.msg('上传文件失败！');
            // layer.msg("网络错误，请稍后再试")
            // layer.closeAll(); //疯狂模式，关闭所有层
        });
        // $.ajax({
        //     url: '/api/Upload/allUpload',
        //     type: 'post',
        //     headers:{
        //         token:window.localStorage.getItem('token')
        //     },
        //     data:formData,
        //     dataType: 'json',
        //     cache : false,
        //     processData : false,
        //     contentType : false,
        //     success: function (res) {
        //         layer.closeAll();
        //         if (res.code==200){
        //             editor.execCommand('insertHtml', '<img data-width="'+width+'" data-height="'+height+'" style="margin: 10px auto;display: block;max-width: 100%!important;" _src="'+res.data.all_path+'" src="'+res.data.all_path+'">');
        //             dialog.close();
        //         }else{
        //             layer.msg(res.msg)
        //         }
        //     },
        //     error:function(){
        //         layer.msg("网络错误，请稍后重试")
        //     }
        // });
    }
    function dataURLtoFile(dataurl, filename) {//将base64转换为文件
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type:mime});
    };
</script>
</body>
</html>